import uuid
from typing import Optional

from fastapi import APIRouter, Body, HTTPException
from pydantic import BaseModel, Field, ValidationError

from app.core.chains import get_introduction_practice_chain, get_introduction_improvement_chain, get_job_match_chain
from app.core.memory.memory_manager import get_session_history
from app.core.prompts import job_match_prompt

router = APIRouter()


class Job_Match_ChatRequest(BaseModel):
    info: str = Field(..., description="User's question for the knowledge base.")
    conversation_id: Optional[str] = Field(None,
                                           description="A unique ID for the conversation. If not provided, a new one will be generated.")

class Job_Match_ChatResponse(BaseModel):
    result: str
    conversation_id: str


@router.post("/", response_model=Job_Match_ChatResponse)
def knowledge_base_chat(request_data: dict = Body(...)):
    """
    Handles a stateful chat request against the knowledge base.
    Uses conversation_id to maintain context.
    """
    try:
        # 手动验证请求数据
        request = Job_Match_ChatRequest(**request_data)
    except ValidationError as e:
        # 打印详细的验证错误
        print(f"请求数据验证失败: {e.errors()}")
        print(f"收到的请求数据: {request_data}")
        raise HTTPException(status_code=422, detail=e.errors())
    conv_id = request.conversation_id or str(uuid.uuid4())
    chat_history_backend = get_session_history(conv_id)
    job_match_chain = get_job_match_chain()
    enhanced_query = (
        f"用户输入的技能为: {request.info}\n"
    )
    print('enhanced_query:', enhanced_query)

    result = job_match_chain.invoke({
        "input": enhanced_query,
        "chat_history": chat_history_backend.messages
    })

    answer = result.get("answer", "I'm sorry, I couldn't find an answer.")
    print(f"{answer}")
    chat_history_backend.add_user_message(enhanced_query)
    chat_history_backend.add_ai_message(answer)

    answerList =  extract_colon_content(answer)

    print (answerList)

    return Job_Match_ChatResponse(
        result= answer,
        conversation_id=conv_id
    )

import re

def extract_colon_content(text):
    """提取所有冒号后的内容（支持多行）"""
    pattern = r'(?:^|\n)(?:.*?[:：]\s*)(.*?)(?=(?:\n.*?[:：]|$))'
    matches = re.findall(pattern, text, re.DOTALL)
    return [match.strip() for match in matches]
